
class FlashClient
{


    public static var me : FlashClient;

    public static var sock : flash.net.Socket;

    public static var timer : flash.utils.Timer;

    public static var chatbox : flashmv.gui.ChatBox;

    public static var ballspr : flash.display.Sprite;
    public static var ball : general.components.SimpleMovable;

    public function new()
    {

        ball = new general.components.SimpleMovable(new general.Component(0,0));

        ballspr = new flash.display.Sprite();
        ballspr.graphics.beginFill(0xCC4444);
        ballspr.graphics.drawCircle(0,0,32);

        timer = new flash.utils.Timer(10);
        timer.addEventListener(flash.events.TimerEvent.TIMER, doPredict);
        timer.start();

        sock = new flash.net.Socket();
        sock.endian = (flash.utils.Endian.LITTLE_ENDIAN);
        sock.addEventListener(flash.events.Event.CONNECT, onConnect);
        sock.addEventListener(flash.events.ProgressEvent.SOCKET_DATA, onData);
        sock.connect("localhost",32100);    
        
        chatbox = new flashmv.gui.ChatBox(800,600,35);
        
        flash.Lib.current.addChild(chatbox);
        flash.Lib.current.addChild(ballspr);
    }

    public static function main()
    {
        me = new FlashClient();
    }
    
    public static function onConnect(e : Dynamic)
    {
        chatbox.out("connect");
    }

    public static function doPredict(e : flash.events.TimerEvent)
    {
        try
        {
        var predictball = ball.predict();
        ballspr.x = predictball[0];
        ballspr.y = predictball[1];
        }
        catch(d : Dynamic) {}
    }
            
    public static function onData(e : Dynamic)
    {
    
        var cmd = sock.readUnsignedByte();
        // we're ignoring cmd until we have more events to read
        var strdata = general.ReadEvent.extended(sock);

        switch (strdata.charAt(0))
        {
            default:
                //silently ignore what I don't understand
                
                //if testing for bad server data, try this:
                //throw e;
                
            case("e"): // echo
                chatbox.out(strdata.substr(1));
            case("E"): // error
                chatbox.out("ERROR: "+strdata.substr(1));
            case("n"): // navigation
                var vals : Array<Int> = new Array();
                var spl : Array<String> = strdata.substr(1).split(":");

                ball.comp.data = new Array();

                for (n in 0...spl.length)
                {
                    ball.comp.data.push( general.NumberEncoding.decodeInt(spl[n]) );
                }

                ball.onUpdate();
        }
    }
    
}